package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.PageVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "用户接口")
@RestController
@RequestMapping("users")
@RequiredArgsConstructor
public class UserController {
    private final IUserService userService;

    @PostMapping
    @ApiOperation("新增用户")
    void saveUser(@RequestBody UserFormDTO userFormDTO) {
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        userService.save(user);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    void deleteUser(@PathVariable Long id) {
        userService.removeById(id);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询用户")
    UserVO getUserById(@PathVariable Long id) {
        // 查询用户
        User user = userService.getById(id);
        if(user == null)
            return null;
        // 根据用户id查询地址信息，select * from address where user_id = #{id}
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        //封装userVO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        userVO.setAddresses(addressVOS);
        return userVO;
    }

    @GetMapping
    @ApiOperation("根据多个ID批量查询用户")
    List<UserVO> getUserByIds(@RequestParam("ids") List<Long> ids) {
        // 查询用户
        List<User> users = userService.listByIds(ids);
        if (users == null || users.isEmpty()) {
            return null;
        }
        List<UserVO> userVOS = new ArrayList<>(users.size());
        // 查询每个用户的地址信息，逐个用户查找
        for (User user : users) {
            Long id = user.getId();
            List<Address> addresses = Db.lambdaQuery(Address.class)
                    .eq(Address::getUserId, id)
                    .list();
            List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(addressVOS);
            userVOS.add(userVO);
        }
        return userVOS;
    }

    @PutMapping("/{id}/deduction/{money}")
    @ApiOperation("扣减用户余额")
    void deductBalance(@PathVariable Long id, @PathVariable Integer money) {
        userService.deductBalance(id, money);
    }

    @GetMapping("/list")
    @ApiOperation("用户条件查询")
    List<UserVO> listUser(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        Integer minBalance = userQuery.getMinBalance();
        Integer maxBalance = userQuery.getMaxBalance();

        List<User> users = userService.lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
        if (users == null || users.isEmpty()) {
            return null;
        }
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @GetMapping("/page")
    @ApiOperation("分页条件查询")
    public PageVO<UserVO> pageQueryUser(UserQuery query) {
        // 分页参数
        Page<User> p = Page.of(query.getPageNo(), query.getPageSize());
        p.addOrder(new OrderItem(query.getSortBy(), query.getIsAsc()));
        // 条件参数
        String name = query.getName();
        Integer status = query.getStatus();
        Integer minBalance = query.getMinBalance();
        Integer maxBalance = query.getMaxBalance();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .like(name != null, User::getUsername,  name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance);
        // 分页查询
        Page<User> page = userService.page(p, wrapper);
        // 封装结果
        PageVO<UserVO> userPageVO = new PageVO<>();
        userPageVO.setTotal(page.getTotal());
        userPageVO.setPages(page.getPages());
        userPageVO.setList(BeanUtil.copyToList(page.getRecords(), UserVO.class));

        return userPageVO;
    }
}

